package send

import (
	"context"
	"gitee.com/pkg/api/events"
	"gitee.com/pkg/root"
	"gitee.com/pkg/utils/flag"
	"gitee.com/pkg/version"
	"gitee.com/pkg/vvlog"
	cloudevents "github.com/cloudevents/sdk-go/v2"
	"github.com/cloudevents/sdk-go/v2/event"
	cehttp "github.com/cloudevents/sdk-go/v2/protocol/http"
	"github.com/spf13/cobra"
)

var (
	logger  = vvlog.NewLogger("send.go")
	url     string
	sendCmd = &cobra.Command{
		Use:   "send",
		Short: "send cloudevent",
		RunE: func(c *cobra.Command, args []string) error {
			flag.PrintFlags(c.Flags())
			runc()
			return nil
		},
	}
)

func init() {
	sendCmd.PersistentFlags().StringVar(&url, "url", "http://localhost:"+version.DefaultPort+"/events", "send to target url")
	root.AddCmd(sendCmd)
}
func runc() {
	ctx := cloudevents.ContextWithTarget(context.Background(), url)

	p, err := cloudevents.NewHTTP()
	if err != nil {
		logger.Fatalf("failed to create protocol: %s", err.Error())
	}

	c, err := cloudevents.NewClient(p, cloudevents.WithTimeNow(), cloudevents.WithUUIDs())
	if err != nil {
		logger.Fatalf("failed to create client, %v", err)
	}

	for i := 0; i < 1; i++ {

		res := c.Send(ctx, newEvent(i))
		if cloudevents.IsUndelivered(res) {
			logger.Printf("Failed to send: %v", res)
		} else {
			var httpResult *cehttp.Result
			cloudevents.ResultAs(res, &httpResult)
			logger.Printf("Sent %d with status code %d", i, httpResult.StatusCode)
		}
	}
}

func newEvent(id int) event.Event {
	e := cloudevents.NewEvent()
	e.SetType("tester")
	e.SetSource("http://localhost:" + version.DefaultPort + "/testor")
	_ = e.SetData(cloudevents.ApplicationJSON, events.PayLoad{
		Message: "hello worlad ",
		Status:  "ok",
	})
	return e
}
